import React from 'react';
import { Upload, Icon, message } from 'antd';
import { connect } from 'dva';
import { UrlConfig } from "../../../services/fetch";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  if (!isJPG && !isPNG) {
    message.error('只能上传jpg/png格式图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2M');
    return false;
  }
  return true;
}

@connect(({ add }) => ({
  add: add
}))
export default class UploadImg extends React.Component {
  state = {
    loading: false,
    imageUrl: `${UrlConfig}/application/fcpublic/resource/images/default.png`
  };
  componentDidMount() {
      
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    // if(nextProps.add.articleData[0].data){
    //     return { imageUrl: nextProps.add.articleData[0].data }
    // }
    if (nextProps.img) {
      return { imageUrl: nextProps.img }
    }
    return null
  }
  

  /**
* 上传插件
*/
  fcUpload = (key) => {
    window.fc = new window.FcUpload({
      elem: 'fcUpload',
      oss: this.props.add.configJson.aliyunOssSwitch,       //是否为oss 上传
      multiple: false,  //是否允许上传多个文件
      type: 'img', // 上传文件类型\ img 图片，  video 视频
      actionImg: `${UrlConfig}/fcpublic/uploads/uploadImg`,  //本地上传图片地址
      actionVideo: `${UrlConfig}/fcpublic/uploads/uploadVideo`,  //本地上传视频地址
      actionOss: this.props.add.configJson.actionOss,  //后端认证接口，获取临时上传凭证
      endpoint: this.props.add.configJson.endpoint,
      bucket: this.props.add.configJson.bucket,
      customDomain : this.props.add.configJson.customDomain,
      ossConfig: this.props.add.configJson,
      callback: (callRes) => {
        let url;
        if (callRes.oss) {  // oss 和本地返回数据结构不一样
          url = callRes.response[0];
        } else {
          url = callRes.response[0].data;
        }
        this.props.setUrl(url)
      }
    })

    window.fc.show();
  }

  render() {
    const imageUrl = this.state.imageUrl;
    return (
      <img src={imageUrl} onClick={this.fcUpload} alt="avatar" width="144px" height="144px" />
    );
  }
}
